package com.access.boot.apisdk.executor;

import lombok.extern.slf4j.Slf4j;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author Yangzhen
 * @date 2022/8/9 11:23
 * @since 1.0.0
 */
@Slf4j
public class HttpRequestExecutor {

    private OkHttpClient client;

    private Integer maxIdleConnections = 10;
    private Integer keepAliveSecond = 60;
    private Integer callTimeout = 5;
    private Integer connectTimeout = 5;
    private Integer readTimeout = 5;
    private Integer writeTimeout = 5;
    private Boolean retryOnConnectionFailure = true;

    public HttpRequestExecutor() {
        this.initOkHttp3();
    }

    public void initOkHttp3() {
        OkHttpClient.Builder okHttpBuilder = new OkHttpClient.Builder()
                .connectionPool(new okhttp3.ConnectionPool(maxIdleConnections,
                        keepAliveSecond, TimeUnit.SECONDS))
                .callTimeout(callTimeout, TimeUnit.SECONDS)
                .connectTimeout(connectTimeout, TimeUnit.SECONDS)
                .readTimeout(readTimeout, TimeUnit.SECONDS)
                .writeTimeout(writeTimeout, TimeUnit.SECONDS)
                .retryOnConnectionFailure(retryOnConnectionFailure);
        this.client = okHttpBuilder.build();
    }

    public String doExecute(Request request) throws IOException {
        Call call = client.newCall(request);

        try (Response execute = call.execute()) {
            if (execute.isSuccessful()) {
                try (ResponseBody responseBody = execute.body()) {
                    return responseBody.string();
                }
            } else {
                log.error("Response(code={}) is not successful for request: {}", execute.code(), request.url().url().toString());
            }
        }
        return null;
    }
}
